package cmd

import (
	"happy-sudoku/tools/datagen/internal/driver"
	"os"

	"github.com/jinzhu/gorm"
	// sqlite driver for gorm
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	"github.com/mkideal/cli"
)

func databaseCmd(cfg *databaseT) error {
	db, err := gorm.Open("sqlite3", cfg.DBPath)
	if err != nil {
		return err
	}
	puzzleGen := driver.NewPuzzleGen(driver.PuzzleGenCfg{
		DB: db,
	})

	csvReader, err := os.Open(cfg.CSVFilePath)
	if err != nil {
		return err
	}

	err = puzzleGen.GenerateFromCsv(csvReader)
	if err != nil {
		return err
	}
	return nil
}

type databaseT struct {
	cli.Helper
	DBPath      string `cli:"*dbpath" usage:"The database path"`
	CSVFilePath string `cli:"*csv" usage:"The CSV file path"`
}

// Database is a sub command
var Database = &cli.Command{
	Name: "database",
	Desc: "generate data in database",
	Argv: func() interface{} { return new(databaseT) },
	Fn: func(ctx *cli.Context) error {
		argv := ctx.Argv().(*databaseT)
		return databaseCmd(argv)
	},
}
